<template>
  <div class="form-setting-panel">
    <!-- start 标题 -->
    <div class="form-setting-group form-common-setting">
      <h3 class="form-setting-panel-title">{{ field.displayName }}</h3>
      <div class="form-design-warning">{{$t('common.form.tip.systemTemplateTips')}}</div>
    </div>
    <!-- end 标题 -->

    <!-- start 编号规则 -->
    <div class="form-setting-group rule-item">
      <div class="rule-header">
        <span class="form-item-title">{{$t('common.serialNumber.numberingRule')}}</span>
        <span @click="openRulesSetting" class="setting">{{$t('common.base.setting')}}</span>
      </div>

      <base-nest-draggable :lists="ruleLists" listKey="settingType">
        <div v-for="(listsItem, index) in ruleLists" :key="index" class="rule-perview" slot="item">
          <!-- start 提交日期 -->
          <div v-if="listsItem.settingType === 'DateNumberSetting' && listsItem.validFlag">
              <i class="iconfont icon-tuozhuaipaixu"></i>
              <span>{{$t('common.serialNumber.DateNumberSetting')}}：</span>
              <span>{{ dateFormatLanguage(listsItem.dateFormat) }}</span>
          </div>
          <!-- end 提交日期 -->
          <!-- start 自增位数 -->
          <div  v-if="listsItem.settingType === 'AutoincrementRule'">
              <i class="iconfont icon-tuozhuaipaixu"></i>
              <span>{{$t('common.serialNumber.AutoincrementRule')}}：</span>
              <span>{{ listsItem.incrFormatV }}</span>
              <span>
                {{$t('common.serialNumber.place')}}，{{$t('common.serialNumber.just')}}
              </span>
              <span>{{ resetTimeLanguage(listsItem.resetTime) }}</span>
          </div>
          <!-- end 自增位数 -->
          <!-- start 固定字符 -->
          <div  v-if="listsItem.settingType === 'CharacterSetting' && listsItem.validFlag">
              <i class="iconfont icon-tuozhuaipaixu"></i>
              <span>{{$t('common.serialNumber.CharacterSetting')}}：</span>
              <span>{{ listsItem.character }}</span>
          </div>
          <!-- end 固定字符 -->

          <!-- start 产品类型 -->
          <div  v-if="listsItem.settingType === 'catalog' && listsItem.validFlag ">
            <i class="iconfont icon-tuozhuaipaixu"></i>
            <span>{{$t('common.base.productType')}}：</span>
            <span>{{ listsItem.catalogFieldDisplayName }}</span>
          </div>
          <!-- end 产品类型 -->
        </div>
      </base-nest-draggable>
    </div>
    <!-- end 编号规则 -->

    <!-- start 字段权限 -->
    <div class="form-setting-group form-setting-item" v-if="isTaskModeForVisibleCustomer">
      <h4 class="form-item-title">{{$t('common.base.fieldPermissions')}}</h4>
      <div class="form-item-box">
        <!-- 是否对客户可见 -->
        <form-visible-customer-setting :disabled="true" :field="field" @input="update"></form-visible-customer-setting>
      </div>
    </div>
    <!-- end 字段权限 -->
    <!-- start 编号规则设置弹窗 -->
    <base-modal
        :title="$t('common.serialNumber.settingRule')"
        :show.sync="visible"
        min-width="680px"
        class="batch-editing-customer-dialog"
        @close="onClose"
      >
      <div class="rule-content">
        <el-form label-position="left" :model="dialogFormData" ref="ruleModalFormRef" label-width="0px">
          <base-nest-draggable :lists="dialogFormData.lists">
            <div v-for="(listsItem,listIndex) in dialogFormData.lists" class="draggable-item" :key="listsItem.settingType" slot="item">
              <!-- start 固定字符 -->
              <div class="drag-icon">
                <i class="iconfont icon-tuozhuaipaixu"></i>
              </div> 
              <!-- label必填不能用原生的，样式更改无效！！！ -->
              <div class="item-label" :class="{'item-label-dot': listsItem.validFlag}">{{labelLanguage(listsItem.settingType)}}</div>
              <el-form-item
                v-if="listsItem.settingType === 'CharacterSetting'"
                class="custom-form-item"
                :prop="'lists.' + listIndex + '.character'"
                :rules="[
                  {
                    required: listsItem.validFlag, message: `${$t('common.serialNumber.characterRule')}`, trigger: 'change'
                  },
                ]"
              >
                <div class="custom-div">
                  <el-input maxlength="5" :placeholder="$t('common.serialNumber.characterVerify')" v-model="listsItem.character" clearable></el-input>
                   <el-switch
                    class="icon-btn"
                    v-model="listsItem.validFlag"
                    @change="(value)=>{saveDispatchRuleSwitch(listsItem, value)}"
                  />
                </div>
              </el-form-item>
              <!-- end 固定字符 -->

              <!-- start 产品类型 -->
              <el-form-item
                v-if="listsItem.settingType === 'catalog'"
                class="custom-form-item"
                :prop="'lists.' + listIndex + '.productStr'"
                :rules="{
                  required: listsItem.validFlag, message: `${$t('common.serialNumber.catalogRule')}`, trigger: 'change'
                }"
              >
                <div class="custom-div">
                  <el-select v-model="listsItem.productStr" @change="(value)=>{getProductItem(listIndex, value)}" :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="(item,index) in productList"
                      :key="index"
                      :label="item.displayName"
                      :value="item.fieldName"
                    ></el-option>
                  </el-select>
                  <el-switch
                    class="icon-btn"
                    v-model="listsItem.validFlag"
                    @change="(value)=>{saveDispatchRuleSwitch(listsItem, value)}"
                  />
                </div>
              </el-form-item>
              <!-- end 产品类型 -->
            
              <!-- start 提交日期 -->
              <el-form-item  class="custom-form-item" v-if="listsItem.settingType==='DateNumberSetting'">
                <div class="custom-div">
                  <el-select v-model="listsItem.dateFormat" @change="(value)=>{dateFormatChange(listIndex, value)}" :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="(item,index) in dateNumberOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.dataForamt"
                    ></el-option>
                  </el-select>
                  <el-switch
                    class="icon-btn"
                    v-model="listsItem.validFlag"
                    @change="(value)=>{saveDispatchRuleSwitch(listsItem, value)}"
                  />
              </div>
              </el-form-item>
              <!-- end 提交日期 -->

              <!-- start 自增位数 -->
              <el-form-item  class="custom-form-item"  v-if="listsItem.settingType === 'AutoincrementRule'">
                <div class="custom-div">
                 <el-select v-model="listsItem.incrFormatV" :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="(item,index) in digitOptions"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                  <div class="just-text">
                    {{$t('common.serialNumber.place')}},{{$t('common.serialNumber.just')}}
                  </div>
                  <el-select v-model="listsItem.resetTime" :disabled="dateTimeDisabled" @change="(value)=>{resetTimeChange(value)}"  :placeholder="$t('common.placeholder.select')">
                    <el-option
                      v-for="(item,index) in autoincrementOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.resetTime"
                      :disabled="item.isDisable"
                    ></el-option>
                  </el-select>
                  <el-switch
                    class="icon-btn"
                    v-model="listsItem.validFlag"
                    disabled
                    @change="(value)=>{saveDispatchRuleSwitch(listsItem, value)}"
                  />
              </div>
              </el-form-item>
              <!-- end 自增位数 -->
            </div>
          </base-nest-draggable>
        </el-form>
      </div>
      <div class="serial-number-perview">{{$t('common.base.preview')}}：{{ serialNumberPerview }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="onSubmit">
          {{ $t('common.base.makeSure') }}
        </el-button>
      </div>
    </base-modal>
    <!-- end 编号规则设置弹窗 -->
  </div>
</template>

<script>
/* mixin */
import SettingMixin from '@src/component/form/mixin/setting';
/* props */
import { settingProps } from '@src/component/form/components/props';

import { getProductMenuField } from "@src/api/ProductV2Api";
import { isTaskNoRepeat } from "@src/api/SettingApi"
/* compontents */
import draggable from "vuedraggable";
import locales from '@src/locales';
/* util */
import { formatDate } from 'pub-bbx-utils';
import { getRootWindow } from "@src/util/dom";
export default {
  name: 'form-serial-number-setting',
  mixins: [SettingMixin],
  props: settingProps,
  components: {
    draggable,
  },
  data() {
    return {
      form: {},
      visible: false,
      // 编号预览
      serialNumberPerview: '',
      // 弹窗数据
      lists: [],
      ruleModalFormRef: {},
      dialogFormData: {
        lists: []
      },
      // setting数据、、提交数据   只有四个规则 提交日期/自增位数/固定字符/产品类型
      ruleLists:  this.field.setting?.serialNumberSetting || [],
      // 默认值 修复后端返回空数组的情况
      rulesType: (this.field.setting?.serialNumberSetting?.length) || [
        { label: this.$t('common.serialNumber.CharacterSetting'), settingType: 'CharacterSetting', character: `T${this.field.setting.rank || ''}`, validFlag: true },
        { label: this.$t('common.base.productType'), settingType: 'catalog', productStr: '', validFlag: false },
        { label: this.$t('common.serialNumber.DateNumberSetting'), settingType: 'DateNumberSetting', dateFormat: 'YYYYMMDD',dateFormatLabel: this.$t('common.serialNumber.ymd'), validFlag: true },
        { label: this.$t('common.serialNumber.AutoincrementRule'), settingType: 'AutoincrementRule', incrFormatV: 6, resetTimeLabel: this.$t('common.serialNumber.resetD'), resetTime: 'today', validFlag: true },
      ],
      // 提交日期下拉
      dateNumberOptions: [
        {
          dataForamt: 'YYYYMMDD',
          label: this.$t('common.serialNumber.ymd')
        },
        {
          dataForamt: 'YYYYMM',
          label: this.$t('common.serialNumber.ym')
        },
        {
          dataForamt: 'YYYY',
          label: this.$t('common.serialNumber.y')
        },
      ],
      // 自增位数下拉
      digitOptions: [5, 6, 7, 8, 9, 10],
      autoincrementOptions: [
        {
          label: this.$t('common.serialNumber.resetN'),
          resetTime: '',
          isDisable: false,
        },
        {
          label: this.$t('common.serialNumber.resetD'),
          resetTime: 'today',
          isDisable: false,
        },
        {
          label: this.$t('common.serialNumber.resetM'),
          resetTime: 'month',
          isDisable: false,
        },
        {
          label: this.$t('common.serialNumber.resetY'),
          resetTime: 'year',
          isDisable: false,
        },
      ],
      productList: [],
      dateTimeDisabled: false, // 默认自增位数下拉框不禁用
    }
  },
  computed:{
    // 华大基因灰度
    bgiPrivate() {
      const RootWindow = getRootWindow(window);
      return Boolean(RootWindow.grayAuth?.['TASK_NO_PRODUCT_TYPE'])
    },
    catalogField(){
      return { label: this.$t('common.base.productType'), settingType: 'catalog', productStr: '', validFlag: false }
    }
  },
  watch: {
    'dialogFormData.lists': {
      handler(newValue) {
        this.serialNumberPerview = '';
        // 根据提交日期筛选按xxx重置
        let resetTime = newValue.find(item=>item.settingType === 'DateNumberSetting');
        if (resetTime?.dateFormat) {
          switch (resetTime?.dateFormat) {
            case "YYYYMM":
              this.autoincrementOptions.map(autoincrementItem => {
                if (autoincrementItem.resetTime === 'today' || autoincrementItem.resetTime === 'week') {
                  autoincrementItem.isDisable = true;
                } else {
                   autoincrementItem.isDisable = false;
                }
              })
              break;
            case "YYYY":
              this.autoincrementOptions.map(autoincrementItem => {
                if (autoincrementItem.resetTime === 'year' || autoincrementItem.resetTime === '') {
                  autoincrementItem.isDisable = false;
                } else {
                  autoincrementItem.isDisable = true;
                }
              })
              break;
            default:
              this.autoincrementOptions.map(autoincrementItem => {
                autoincrementItem.isDisable = false;
              })
              break;
          }
        }
        newValue.map(item => {
          switch (item.settingType) {
            case "DateNumberSetting":
              // 获取当前年月日,拼接预览编号
              if (item.validFlag) {
                const date = formatDate(new Date(), item.dateFormat);
                this.serialNumberPerview += date;
              }
              break;
            case "AutoincrementRule":
              item.incrFormat = this.autoaccretion(1, item.incrFormatV);
              this.serialNumberPerview += item.incrFormat;
              break;
            case "CharacterSetting":
              if (item.validFlag) {
                this.serialNumberPerview += item.character
              }
              break;
            case "catalog":
              if (item.validFlag && item.catalogFieldDisplayName) {
                this.serialNumberPerview += item.catalogFieldDisplayName
              }
              break;
          }
        })
      },
      deep: true,
      immediate: true,
    },
    ruleLists: {
      handler(newValue) {
        if (newValue) {
          newValue.forEach((item) => {
            // 产品类型字段国际化匹配修改
            if (item.settingType === 'catalog') {
              item.catalogFieldDisplayName = item.displayNameLanguage?.[locales.locale] || item.displayName
            }
          })
          const existCatalogFieldIndex = newValue.findIndex(item=> item.settingType === 'catalog')
          !this.bgiPrivate && existCatalogFieldIndex > -1 && newValue.splice(existCatalogFieldIndex, 1)
        }
        this.field.setting.serialNumberSetting = newValue;
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    dateFormatLanguage(val) {
      if (!val) return ''
      return this.dateNumberOptions.filter((item) => item.dataForamt === val)?.[0]?.label || ''
    },
    resetTimeLanguage(val) {
      return this.autoincrementOptions.filter((item) => item.resetTime === val)?.[0]?.label || ''
    },
    labelLanguage(val) {
      let labelName = {
        'CharacterSetting': this.$t('common.serialNumber.CharacterSetting'),
        'catalog': this.$t('common.base.productType'),
        'AutoincrementRule': this.$t('common.serialNumber.AutoincrementRule'),
        'DateNumberSetting': this.$t('common.serialNumber.DateNumberSetting')
      }
      return labelName[val]
    },
    dateFormatChange(index, value) {
      let currentItem = this.dateNumberOptions.filter((item) => item.dataForamt === value)[0]
      this.dialogFormData.lists.map((item, index) => {
        // 提交日期
        if (item.settingType === 'DateNumberSetting') {
          item.dateFormatLabel = currentItem.label
        }

        // 提交日期改变的话，自增位数重置的值清除
        if (item.settingType === 'AutoincrementRule') {
          item.resetTime = ''
          item.resetTimeLabel = this.$t('common.serialNumber.resetN')
        }
      })
    },

    // 重置下拉文案修改
    resetTimeChange(val) {
      this.dialogFormData.lists.map((item, index) => {
        // 提交日期改变的话，自增位数重置的值清除
        if (item.settingType === 'AutoincrementRule') {
          item.resetTimeLabel = this.resetTimeLanguage(val)
        }
      })
    },
    /**
   * 获取自增数据
   * @param {Number} number
   * @param {Number} digit 字符长度
   */
    autoaccretion (number, digit = 0) {
      if (typeof number !== 'number') { return new Array(digit).fill('0').join(''); }
      const strNumber = number.toString();
      if (strNumber.length >= digit) { return strNumber; }
      const diffLenght = digit - strNumber.length;

      return new Array(diffLenght).fill('0').join('') + strNumber;
    },
    /* 当前编号规则开启/禁用 */ 
    saveDispatchRuleSwitch(row, value) {
      if (row.settingType === 'DateNumberSetting' && !value) {
        // 把下拉框禁用
        this.dateTimeDisabled = true
        this.dialogFormData.lists.map((item, index) => {
        // 提交日期禁用的话，自增要设置为不重置
        if (item.settingType === 'AutoincrementRule') {
            item.resetTime = ''
            item.resetTimeLabel = this.$t('common.serialNumber.resetN')
          }
        })
      } else {
        this.dateTimeDisabled = false
      }
    },
    dataConversion(data) {
      if(!this.bgiPrivate) data = data.filter(item=> item.settingType !== 'catalog')
      return JSON.parse(JSON.stringify(data))
    },
    onSubmit() {
      this.$refs['ruleModalFormRef'].validate(async(valid) => {
          if (valid) {
          let params = {
            typeId: this.field.templateId || '',
            collect: this.dialogFormData.lists
          }
          // 判断是否规则重复
          await isTaskNoRepeat(params).then((res) => {
            if (!res.succ) return
            if (res.data) {
              return this.$message.warning(this.$t('common.serialNumber.repeatRuleNumber'));
            } else {
              // 不重复的话，可以提交
              this.ruleLists = this.dataConversion(this.dialogFormData.lists);
              this.onClose();
            }
          })
          } else {
            console.log('error submit!!');
            return false;
          }
      });

    },
    async openRulesSetting() {
      await this.getProduct()
      this.dateTimeDisabled = false // 默认自增位数下拉框不禁用

      if (this.ruleLists.length > 0) {

        const existCatalogFieldIndex = this.ruleLists.findIndex(item=> item.settingType === 'catalog')
        if(existCatalogFieldIndex < 0) {
          this.bgiPrivate && this.ruleLists.splice(1, 0, this.catalogField)
        } else {
          !this.bgiPrivate && this.ruleLists.splice(existCatalogFieldIndex, 1)
        }

        this.dialogFormData.lists = await this.dataConversion(this.ruleLists);
      } else {
        this.dialogFormData.lists = await this.dataConversion(this.rulesType);
      }

      this.dialogFormData.lists.map((item) => {
        if (item.settingType === 'DateNumberSetting') {
          // 把下拉框禁用
          this.dateTimeDisabled = !item.validFlag
        }
      })

      this.visible = true;
    },
    // 获取当前选中的产品类型字段
    getProductItem(index, value) {
      if (!value) return
      let currentItem = this.productList.filter((item) => item.fieldName === value)[0]
      this.dialogFormData.lists.map((item, index) => {
        if (item.settingType === 'catalog') {
          // 重新赋值
          item.displayName = currentItem.displayName
          item.catalogFieldName = currentItem.fieldName
          item.catalogFieldDisplayName = currentItem.displayName
          item.displayNameLanguage = currentItem.displayNameLanguage
        }
      })
    },
    // 获取产品所有的类型
    async getProduct() {
      this.productList = []
      await getProductMenuField()
      .then((res) => {
        const { code, result, message } = res;
        if (code == 0) {
          // 只选择单行文本/多行文本/下拉框/数字类型的字段
          let formTypeArr = ['text', 'textarea', 'select', 'number']
          result.map((item) => {
            if (formTypeArr.includes(item.formType)) {
              this.productList.push(item)
            }
          })
        } else {
          this.$notify.error({
            title: this.$t('common.base.tip.httpIsError'),
            message,
            duration: 2000,
          });
        }
      })
      .catch((error) => {});
    },

    onClose() {
      this.visible = false;
    },
    updateForDom(event) {
      let el = event.target;
      let prop = el.dataset.prop;
      let value = el.value;

      this.update(value, prop);
    },
    update(value, prop, isSetting = false) {
      this.$emit('input', { value, prop, isSetting });
    }
  }
};
</script>

<style lang="scss" scoped>
.form-setting-group-small {
  margin-bottom: 24px;
}
.rule-item{
  .rule-header{
    display: flex;
    justify-content: space-between;
    padding-right: 10px;
    box-sizing: border-box;
    span:nth-child(1){
      font-weight: 700;
    }
    .setting{
      color: $color-primary-light-6;
      cursor: pointer;
    }
  }
  .rule-perview{
    margin: 15px 0 0 0;
    div{
      i,span{
        margin-left: 5px;
      }
    }
  }
}
.batch-editing-customer-dialog{
  .rule-content{
    padding: 20px 20px;
    box-sizing: border-box;
    ::v-deep .el-dropdown{
      float: left !important;
      margin-bottom: 10px;
      i{
        font-size: 12px !important;
      }
    }
    .draggable-item{
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .custom-form-item {
        width: 100%;
        margin-bottom: 0;
      }
      .item-label{
        text-align: center;
        margin-right: 6px;
        min-width: 106px;
       @include text-ellipsis;

        &.item-label-dot::before {
          content: "*";
          color: #f56c6c;
          margin-right: 4px;
        }
      }
      .custom-div{
        width: 100%;
        display: flex;
        align-items: center;
        margin: 5px 0;
        .just-text{
          text-align: center;
          min-width: 60px;
          margin: 0 4px;
        }
      }

      .icon-btn{
          width: auto;
          padding: 0;
          background: transparent;
          border: none;
          font-size: 16px;
          border-radius: 0;
          margin-left: 14px;
          // margin-top: 8px;
          &:hover {
            color: #d9363e;
          }
        }
    }
  }
}
.serial-number-perview{
  text-align: center;
  margin: 20px 0 5px 0;
}
</style>